<template>
  <div class="star-grade">
    <span v-if="rating.average > 0" :class="[star, 'star']" v-for="star in stars" :key="star.id"></span>
    <span class="score">{{ rating.average > 0 ? rating.average : '暂无评分' }}</span>
  </div>
</template>

<style lang="scss" scoped>
  .star-grade {
    position: absolute;
    width: 90px;
    height: 15px;
    left: 5px;
  }

  .star {
    width: 10px;
    height: 10px;
    position: relative;
    background-size: cover;
    display: inline-block;
  }

  .star-full {
    background-image: url('../assets/images/star-full.png');
  }

  .star-half {
    background-image: url('../assets/images/star-half.png');
  }

  .star-grey {
    background-image: url('../assets/images/star-grey.png');
  }

  .score {
    color: #aaa;
  }

</style>

<script>
  export default {
    data() {
      return {
        stars: []
      }
    },
    props: {
      rating: {
        type: Object,
        required: true
      }
    },
    created() {
      this.renderStars();
    },
    methods: {
      // 根据评分渲染星星
      renderStars() {
        const fullStar = Number.parseInt(this.rating.average / 2);
        for (let i = 0; i < fullStar; i++) {
          this.stars.push('star-full');
        }
        if (fullStar < 5) {
          const restScore = this.rating.average - fullStar * 2;
          if (restScore > 1) {
            this.stars.push('star-full');
          } else if (restScore == 1) {
            this.stars.push('star-half');
          } else {
            this.stars.push('star-grey');
          }
        }
        const restStar = 5 - fullStar - 1;
        if (restStar > 0) {
          for (let i = 0; i < restStar; i++) {
            this.stars.push('star-grey');
          }
        }
      }
    }
  }

</script>
